<template>
    <view  class="bottom">
        <div class="top">
            <div class="top_img" @click="returns">
                <image :src="imageBaseUrl + '/img/backtrack.png'" mode="widthFix"></image>
            </div>
            <div class="top_text">{{ data.name }}</div>
        </div>
        <div class="qrcode" @longtap="saveQrcode">
            <div style="margin-top: 23vh;margin-left: 5vw;">
                <uv-qrcode ref="qrcodeRef" :value="data.order_code" :options="options2"></uv-qrcode>

            </div>
            <view v-if="showToast" class="toast">{{ toastMessage }}</view>
        </div>

    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import config from '../../config/index.js';
const imageBaseUrl = config.image;//图片路径
const data = ref({});//订单信息
// 定义响应式数据
const qrcodeRef = ref(null)//二维码组件
const showToast = ref(false)//显示提示信息
const toastMessage = ref('')//提示信息
// 定义响应式数据
const options2 = ref({
    data: '213123',
    size: 600,
    useDynamicSize: false,
    errorCorrectLevel: 'Q',
})

// 保存二维码方法
const saveQrcode = async () => {
    try {
        // 显示加载提示
        uni.showLoading({
            title: '正在保存...',
            mask: true
        })

        // 获取组件实例
        const qrcode = qrcodeRef.value

        // 加载背景图片
        const backgroundImage = await loadImage(imageBaseUrl + '/img/backdrop.jpg')

        // 创建canvas元素
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')

        // 设置canvas尺寸
        canvas.width = backgroundImage.width
        canvas.height = backgroundImage.height

        // 绘制背景
        ctx.drawImage(backgroundImage, 0, 0)

        // 生成二维码临时路径
        const qrTempFilePath = await new Promise((resolve, reject) => {
            qrcode.toTempFilePath({
                success: (res) => resolve(res.tempFilePath),
                fail: (err) => reject(new Error(`生成二维码失败: ${err.errMsg}`))
            })
        })

        // 加载二维码图片
        const qrImage = await loadImage(qrTempFilePath)

        // 绘制二维码
        const qrSize = Math.min(canvas.width * 0.7, canvas.height * 0.7)
        const x = (canvas.width - qrSize) / 2// 居中
        const y = (canvas.height - qrSize) / 2// 居中
        ctx.drawImage(qrImage, x, y, qrSize, qrSize)

        // 将canvas转换为临时文件路径
        const canvasTempFilePath = await new Promise((resolve, reject) => {
            uni.canvasToTempFilePath({
                canvas,
                success: (res) => resolve(res.tempFilePath),
                fail: (err) => reject(new Error(`Canvas转换失败: ${err.errMsg}`))
            })
        })

        // 保存图片到相册
        await saveImageToAlbum(canvasTempFilePath)

        showToastMessage('保存成功')
    } catch (error) {
        console.error('保存过程出错:', error)

        // 处理权限问题
        if (error.message.includes('auth deny')) {
            uni.showModal({
                title: '权限申请',
                content: '需要相册权限才能保存图片',
                success: (res) => {
                    if (res.confirm) {
                        uni.openSetting()
                    }
                }
            })
        } else {
            showToastMessage(`保存失败: ${error.message}`)
        }
    } finally {
        uni.hideLoading()
    }
}

// 显示提示消息
const showToastMessage = (message) => {
    toastMessage.value = message
    showToast.value = true

    setTimeout(() => {
        showToast.value = false
    }, 2000)
}

// 辅助函数: 加载图片
const loadImage = (src) => {
    return new Promise((resolve, reject) => {
        const img = new Image()
        img.onload = () => resolve(img)
        img.onerror = (err) => reject(new Error(`图片加载失败: ${src}`))
        img.src = src
    })
}

// 返回
const returns = () => {
    uni.navigateBack({
        delta: 1
    })
}
onMounted(() => {
    console.log('组件已挂载')
    data.value = uni.getStorageSync('QR_code')
    console.log(data.value)
})
</script>

<style lang="scss" scoped>
.top_text {
    font-size: 18px;
}

.top_img {
    width: 30px;
    height: 30px;
    margin-left: 20px;
    margin-right: 15%;
    background-color: rgb(0, 0, 0);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.top_img image {
    width: 20px;
    height: 20px;
}

.top {
    display: flex;
    align-items: center;
    padding-top: 30px;
    background-color: #FFFAEC;
}

.bottom {
    background-color: #FFFAEC;
    height: 100vh;
}

.qrcode {
    width: 100%;
    display: flex;
    height: 70vh;
    background-image: url("http://lxj.skych.top//img/backdrop.jpg");
    background-size: cover;
    justify-content: center;
    align-items: center;
    position: relative;
}

.toast {
    position: fixed;
    bottom: 50px;
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 10px 20px;
    border-radius: 20px;
    font-size: 14px;
    z-index: 100;
}
</style>